package com.uchiha.nova.core.utils;

import cn.hutool.core.util.ObjectUtil;
import com.uchiha.nova.core.model.LogAbstract;
import com.uchiha.nova.core.props.NovaProperties;
import com.uchiha.nova.core.props.ServerInfo;
import com.uchiha.nova.core.tool.constant.NovaConstant;
import com.uchiha.nova.core.tool.util.*;
import jakarta.servlet.http.HttpServletRequest;


/**
 * @author 周林静
 * @Date 2021-10-25 15:03
 * @Version 1.0
 */
public class LogAbstractUtil {

    /**
     * 向log中添加补齐request的信息
     *
     * @param request     请求
     * @param logAbstract 日志基础类
     */
    public static void addRequestInfoToLog(HttpServletRequest request, LogAbstract logAbstract) {
        if (ObjectUtil.isNotEmpty(request)) {
            logAbstract.setTenantId(Func.toStrWithEmpty(AuthUtil.getUser().getTenantId(), NovaConstant.ADMIN_TENANT_ID));
            logAbstract.setRemoteIp(WebUtil.getIP(request));
            logAbstract.setUserAgent(request.getHeader(WebUtil.USER_AGENT_HEADER));
            logAbstract.setRequestUri(UrlUtil.getPath(request.getRequestURI()));
            logAbstract.setMethod(request.getMethod());
            logAbstract.setParams(WebUtil.getRequestContent(request));
            logAbstract.setCreateBy(AuthUtil.getUser().getUserId().toString());
        }
    }

    /**
     * 向log中添加补齐其他的信息（eg：blade、server等）
     *
     * @param logAbstract     日志基础类
     * @param novaProperties 配置信息
     * @param serverInfo      服务信息
     */
    public static void addOtherInfoToLog(LogAbstract logAbstract, NovaProperties novaProperties, ServerInfo serverInfo) {
        logAbstract.setServiceId(novaProperties.getName());
        logAbstract.setServerHost(serverInfo.getHostName());
        logAbstract.setServerIp(serverInfo.getIpWithPort());
        logAbstract.setCreateTime(DateUtil.now());
        if (logAbstract.getParams() == null) {
            logAbstract.setParams(StringPool.EMPTY);
        }
    }
}
